<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import InfoCard from '../infocard/InfoCard.vue';
import { IInfoCard, IPowerSetting, IPSUList } from '@/model/System/power-interface';
import { deepClone } from '@/utils/utils';
import { getpowerSupply, setPowerSupply } from '../../services/power.services';
import HelpIcon from '@/components/HelpIcon/HelpIcon.vue';
import { traduction } from '@/utils/language';
import { showElMessage } from '@/utils/utils';
import { loading, getStoreData } from '@/utils/composition';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import powerTag from './components/PowerTag.vue';
import { ENERGY_PAGE_ENABLED } from '@/model/configure';

// 系统锁定
const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
const locale = getStoreData('loct', 'locale');
const isPrivileges = checkPrivil(UserPrivil.powerControl);
const saveBtnState = ref(false);
let infoList: IInfoCard[] = reactive([]);
let dialogFormVisible = ref(false);
const powerSetting: IPowerSetting = reactive({
  workingMode: null,
  activePSU: [],
  deepSleep: '',
  normalAndRedundancy: null,
});
let oldData = reactive({});
let isActiveAndStandby = '';
let deepSleep = ref(false);
let workingModeDisabled = ref(true);
const activePSUList = ref([]);
const activePSU = ref('');
let configParam: Object | null = {};
const isPowerSetting = ref(true);
const pageLoaded = ref(false);
const deepSleepSupported = ref(true);
const activeStandbySupported = ref(true);
const commandMode = ref('');
// 初始化
function init() {
  loading(true);
  infoList.splice(0);
  powerSetting.activePSU = [];
  activePSUList.value = [];
  activePSU.value = '';
  getpowerSupply()
    .then(res => {
      loading(false);
      commandMode.value = res?.data?.RecommendedPowerMode || '';
      powerSetting.workingMode = res.data.PowerMode;
      powerSetting.deepSleep = res.data.DeepSleep;
      powerSetting.normalAndRedundancy = res.data.NormalAndRedundancy === 'Enabled';
      const recommendedData = [] as any[];
      if (res?.data?.RecommendedActiveSupplies) {
        if (res.data.RecommendedActiveSupplies.length !== 0) {
          for (let item of res.data.RecommendedActiveSupplies) {
            recommendedData.push(`PSU${item}`);
          }
        }
      }
      res?.data?.ExpectedSupplyList?.forEach((item: any, index: number) => {
        let obj: IPSUList = reactive({
          name: item.Name,
          mode: item.Mode,
          isCommand: false,
        });
        if (recommendedData.length !== 0 && recommendedData.includes(item.Name)) {
          obj.isCommand = true;
        }
        powerSetting.activePSU.push(obj);
      });
      res?.data?.SupplyList?.forEach((item: any) => {
        const obj = deepClone(item);
        infoList.push(obj);
      });
      isActiveAndStandby = powerSetting.workingMode as string;
      deepSleepSupported.value = res.data.DeepSleepSupported;
      activeStandbySupported.value = res.data.ActiveStandbySupported;
      if (powerSetting.workingMode && powerSetting.deepSleep === null) {
        isPowerSetting.value = false;
      }
      if (res.data.ActiveStandbySupported === false || !ENERGY_PAGE_ENABLED) {
        isPowerSetting.value = false;
      }
      pageLoaded.value =true;
    })
    .then(() => {
      loading(false);
      pageLoaded.value =true;
      initDialog();
      Object.assign(oldData, deepClone(powerSetting));
      computedState();
    });
}

// 切换工作模式
function workingModeChange(val: any) {
  if (val === 'Active/Standby') {
    workingModeDisabled.value = false;
  } else if (val === 'Sharing') {
    workingModeDisabled.value = true;
    activePSUList.value = [];
    activePSU.value = '';
  }
  computedState();
}
function activePowerChange(val: any) {
  if (powerSetting.activePSU.length === 2) {
    powerSetting.activePSU.forEach(item => {
      if (activePSU.value === item.name) {
        item.mode = 'Active';
      } else {
        item.mode = 'Standby';
      }
    });
  } else {
    powerSetting.activePSU.forEach(item => {
      if (activePSUList.value.indexOf(item.name as never) !== -1) {
        item.mode = 'Active';
      } else {
        item.mode = 'Standby';
      }
    });
  }
  computedState();
}
function deepDormancyChange(val: boolean) {
  if (val) {
    powerSetting.deepSleep = 'On';
  } else {
    powerSetting.deepSleep = 'Off';
  }
  computedState();
}
// 设置
function powerConfig() {
  if (configParam === 1) {
    showElMessage('error', traduction('POWER_NO_STAND'));
  } else if (configParam === 2) {
    showElMessage('error', traduction('POWER_SELECT_MAIN'));
  } else {
    loading(true);
    setPowerSupply(configParam)
      .then(res => {
        loading(false);
        dialogFormVisible.value = false;
        if (res.data.error) {
          const msg = traduction(res.data.error[0].code + '.errorMessage');
          showElMessage('error', msg);
        } else {
          showElMessage('success', traduction('COMMON_SUCCESS'));
        }
        init();
      })
      .catch(error => {
        loading(false);
        dialogFormVisible.value = false;
        showElMessage('error', traduction('COMMON_FAILED'));
        init();
      });
  }
}

// 提交
const onSubmit = () => {
  powerConfig();
};

function closeDialog() {
  dialogFormVisible.value = false;
  Object.assign(powerSetting, deepClone(oldData));
  initDialog();
  computedState();
}

function initDialog() {
  activePSUList.value = [];
  activePSU.value = '';
  powerSetting.activePSU.forEach((item: any, index: number) => {
    if (item.mode === 'Active') {
      (activePSUList.value as any).push(item.name);
      activePSU.value = item.name;
    }
  });
  if (powerSetting.workingMode === 'Active/Standby') {
    workingModeDisabled.value = false;
  } else {
    workingModeDisabled.value = true;
  }
  deepSleep.value = powerSetting.deepSleep === 'On' ? true : false;
}

// 保存按钮的状态
function computedState() {
  getParam();
  if (JSON.stringify(oldData) !== JSON.stringify(powerSetting)) {
    saveBtnState.value = true;
  } else {
    saveBtnState.value = false;
  }
}
function getParam() {
  const param = {};
  let isStandby = 0;
  let deepDormancy = '';
  const supplyList: { Name: string; Mode: string | null }[] = [];
  if (powerSetting.workingMode !== isActiveAndStandby) {
    param['PowerMode'] = powerSetting.workingMode;
  }
  if (powerSetting.workingMode === 'Active/Standby') {
    let isActive = true;
    isStandby = 1;
    powerSetting.activePSU.forEach(item => {
      if (item.mode === 'Active') {
        supplyList.push({
          Name: item.name,
          Mode: 'Active',
        });
        isActive = false;
      } else {
        supplyList.push({
          Name: item.name,
          Mode: 'Standby',
        });
        isStandby = 0;
      }
    });
    if (isActive) {
      isStandby = 2;
    }
    param['SupplyList'] = supplyList;
  }
  if (
    (oldData['deepSleep'] === 'Off' && deepSleep.value) ||
    (oldData['deepSleep'] === 'On' && !deepSleep.value)
  ) {
    deepDormancy = deepSleep.value ? 'On' : 'Off';
    param['DeepSleep'] = deepDormancy;
  }
  if (JSON.stringify(param) !== '{}' && !isStandby) {
    configParam = param;
  } else {
    configParam = null;
    if (JSON.stringify(param) !== '{}') {
      if (isStandby === 1 || isStandby === 2) {
        configParam = isStandby;
      }
    }
  }
  return configParam;
}

onMounted(() => {
  init();
});
</script>

<template>
  <div v-if="pageLoaded" class="page-box">
    <div v-privil.base.powerControl class="power-setting">
      <el-button
        v-if="isPrivileges && isPowerSetting"
        id="powerSetting"
        class="power-setting-btn"
        :disabled="isSystemLock"
        @click="dialogFormVisible = true"
      >
        {{ $t('POWER_SETTING') }}
      </el-button>
      <!-- 电源设置 -->
      <div v-if="dialogFormVisible" v-reqKeepAlive.dialog>
        <el-dialog
          v-model="dialogFormVisible"
          :close-on-click-modal="false"
          :width="locale === 'zh' ? '432px' : '656px'"
          top="412px"
          @close="closeDialog"
        >
          <template #title>
            <div class="flex-style">
              <span class="el-dialog__title">{{ $t('POWER_SETTING') }}</span>
              <HelpIcon
                :append-to-body="true"
                class="help-icon"
                pop-class="help-tip"
                placement="top"
                :tips="$t('POWER_SETTING_TIPS')"
              ></HelpIcon>
            </div>
          </template>
          <el-form :label-width="locale === 'zh' ? 'auto' : '112px'" label-position="left" :model="powerSetting">
            <!-- 工作模式 -->
            <el-form-item class="work-mode" :label="$t('POWER_WORKING_MODE')">
              <el-radio-group
                v-model="powerSetting.workingMode"
                :disabled="powerSetting.normalAndRedundancy"
                @change="workingModeChange"
              >
                <el-radio v-addId.radio="'sharing'" label="Sharing">
                  <div class="radio-content" :class="{ 'foreign-width' : locale !== 'zh' && commandMode !== 'Sharing' }">
                    <div :class="locale === 'zh' ? '' : 'radio-box-text'">{{ $t('POWER_LOAD_BALANCING') }}</div>
                    <div v-if="commandMode === 'Sharing'" class="tag-box">
                      <powerTag/>
                    </div>
                    <div class="empty-box-another" v-else-if="locale === 'zh'"></div>
                  </div>
                </el-radio>
                <el-radio v-addId.radio="'failover'" label="Active/Standby">
                  <div class="radio-content">
                    <div>{{ $t('POWER_MAIN_STANDBY') }}</div>
                    <div v-if="commandMode === 'Active/Standby'" class="tag-box">
                      <powerTag/>
                    </div>
                  </div>
                </el-radio>
              </el-radio-group>
              <HelpIcon
                :append-to-body="true"
                class="help-icon"
                pop-class="help-tip"
                placement="top"
                :tips="$t('POWER_WORKING_MODE_TIP')"
              ></HelpIcon>
            </el-form-item>
            <!-- 主用电源 -->
            <el-form-item v-if="activeStandbySupported" :label="$t('POWER_MAIN')" class="power-check-box">
              <el-radio-group
                v-if="powerSetting.activePSU.length === 2"
                v-model="activePSU"
                :disabled="workingModeDisabled || powerSetting.normalAndRedundancy"
                @change="activePowerChange"
              >
                <el-radio
                  v-for="(item, index) in powerSetting.activePSU"
                  :key="item.name"
                  v-addId.radio="'power' + index"
                  :label="item.name">
                  <div :class="locale === 'zh' ? 'check-box-content-another' : 'check-box-content'" class="flex-style">
                    <span class="check-box-text">{{ item.name }}</span>
                    <div v-if="item.isCommand && !workingModeDisabled" class="tag-box">
                      <powerTag/>
                    </div>
                    <div v-else class="empty-box"> </div>
                  </div>
                </el-radio>
              </el-radio-group>
              <el-checkbox-group
                v-else
                v-model="activePSUList"
                :disabled="workingModeDisabled || powerSetting.normalAndRedundancy"
                @change="activePowerChange"
              >
                <el-checkbox
                  v-for="(item, index) in powerSetting.activePSU"
                  :key="item.name"
                  v-addId.checkbox="'power' + index"
                  :label="item.name"
                >
                <div :class="locale === 'zh' ? 'check-box-content-another' : 'check-box-content'" class="flex-style">
                  <span class="check-box-text">{{ item.name }}</span>
                  <div v-if="item.isCommand && !workingModeDisabled" class="tag-box">
                    <powerTag/>
                  </div>
                  <div v-else class="empty-box"> </div>
                  </div>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <!-- 深度休眠 -->
            <el-form-item v-if="deepSleepSupported" class="deep-sleep">
              <template #label>
                <span>{{ $t('POWER_DEEP_DORMANCY') }}</span>
                <HelpIcon
                  class="help-icon"
                  placement="top"
                  :tips="$t('POWER_OS_SHUTDOWN')"
                ></HelpIcon>
              </template>
              <el-switch id="powerSwitch" v-model="deepSleep" @change="deepDormancyChange" />
            </el-form-item>
            <!-- 设置按钮 -->
          </el-form>
          <template #footer>
            <el-button
              id="powerSetSave"
              :disabled="!saveBtnState"
              size="small"
              type="primary"
              @click="onSubmit"
            >
              {{ $t('COMMON_SAVE') }}
            </el-button>
            <el-button id="powerSetCancel" size="small" @click="closeDialog()">
              {{ $t('COMMON_CANCEL') }}
            </el-button>
          </template>
        </el-dialog>
      </div>
    </div>
    <div class="info-list">
      <!-- 电源信息列表 -->
      <InfoCard v-for="item in infoList" :key="item.id" :data="item" :support="activeStandbySupported"></InfoCard>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.page-box {
  .power-setting-btn {
    margin-top: 16px;
  }
  .power-setting {
    :deep(.el-dialog) {
      min-width: 432px;
      .el-form-item {

        .el-form-item__label {
          padding: 0 24px 0 0;
          height: 16px;
        }
      }
      .el-form-item__label {
        padding-top: 0;
        padding-bottom: 0;
        display: flex;
        align-items: center;
      }

      .el-radio,
      .el-checkbox {
        height: auto;
      }
      .el-radio-group {
        .el-radio,
        .el-checkbox {
          &:nth-child(1) {
            margin-right: 22px;
          }
        }
      }
      .power-check-box {
        .el-checkbox-group {
          .el-radio,
          .el-checkbox {
            &:nth-child(1){
              margin-right: 22px;
            }
            &:nth-child(2n){
              margin-right: 0;
            }
            &:nth-child(2n+1){
              margin-right: 22px;
            }
          }
        }
      }
    }
  }
  .info-list {
    display: flex;
    flex-wrap: wrap;
    
    .card-box{
      margin-top: 16px;
      margin-right: 16px;
    }
  }
  :deep(.el-form-item) {
    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
  .help-icon {
    display: inline-block;
    margin: 0 4px;
  }
}
.check-box-content {
  display: flex;
  align-items: center;
  .check-box-text {
    margin-right: 4px;
  }
  .empty-box {
    width: 120px;
  }
  .tag-box {
    width: 120px;
  }
}
.foreign-width {
  width: 154px;
}
.check-box-content-another {
  .empty-box {
    width: 68px;
  }
  .tag-box {
    margin-left: 4px;
    width: 64px;
  }
}

.radio-content {
  display: flex;
  align-items: center;
  .tag-box {
    margin-left: 4px;
  }
  .empty-box-another {
    width: 50px;
  }
}
.flex-style {
  display: flex;
  align-items: center;
}
</style>
<style>
.help-tip {
  max-width: 381px;
}
</style>
